// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.trees.expressions.functions.scalar;

import org.apache.doris.analysis.DateLiteral;
import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.catalog.ScalarType;
import org.apache.doris.catalog.Type;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.functions.AlwaysNullable;
import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.DateTimeV2Type;
import org.apache.doris.nereids.types.StringType;
import org.apache.doris.nereids.types.VarcharType;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

/**
 * ScalarFunction 'str_to_date'. This class is generated by GenerateFunction.
 */
public class StrToDate extends ScalarFunction
        implements BinaryExpression, ExplicitlyCastableSignature, AlwaysNullable {

    public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
            FunctionSignature.ret(DateTimeV2Type.MAX).args(VarcharType.SYSTEM_DEFAULT,
                    VarcharType.SYSTEM_DEFAULT),
            FunctionSignature.ret(DateTimeV2Type.MAX).args(StringType.INSTANCE, StringType.INSTANCE)
    );

    /**
     * constructor with 2 arguments.
     */
    public StrToDate(Expression arg0, Expression arg1) {
        super("str_to_date", arg0, arg1);
    }

    @Override
    public FunctionSignature computeSignature(FunctionSignature signature) {
        /*
         * The return type of str_to_date depends on whether the time part is included in the format.
         * If included, it is datetime, otherwise it is date.
         * If the format parameter is not constant, the return type will be datetime.
         * The above judgment has been completed in the FE query planning stage,
         * so here we directly set the value type to the return type set in the query plan.
         *
         * For example:
         * A table with one column k1 varchar, and has 2 lines:
         *     "%Y-%m-%d"
         *     "%Y-%m-%d %H:%i:%s"
         * Query:
         *     SELECT str_to_date("2020-09-01", k1) from tbl;
         * Result will be:
         *     2020-09-01 00:00:00
         *     2020-09-01 00:00:00
         *
         * Query:
         *      SELECT str_to_date("2020-09-01", "%Y-%m-%d");
         * Return type is DATE
         *
         * Query:
         *      SELECT str_to_date("2020-09-01", "%Y-%m-%d %H:%i:%s");
         * Return type is DATETIME
         */
        DataType returnType;
        if (getArgument(1) instanceof StringLikeLiteral) {
            if (DateLiteral.hasTimePart(((StringLikeLiteral) getArgument(1)).getStringValue())) {
                returnType = DataType.fromCatalogType(ScalarType.getDefaultDateType(Type.DATETIME));
                if (returnType.isDateTimeV2Type()) {
                    returnType = DataType.fromCatalogType(Type.DATETIMEV2_WITH_MAX_SCALAR);
                }
            } else {
                returnType = DataType.fromCatalogType(ScalarType.getDefaultDateType(Type.DATE));
            }
        } else {
            returnType = DataType.fromCatalogType(ScalarType.getDefaultDateType(Type.DATETIME));
            if (returnType.isDateTimeV2Type()) {
                returnType = DataType.fromCatalogType(Type.DATETIMEV2_WITH_MAX_SCALAR);
            }
        }
        return signature.withReturnType(returnType);
    }

    /**
     * withChildren.
     */
    @Override
    public StrToDate withChildren(List<Expression> children) {
        Preconditions.checkArgument(children.size() == 2);
        return new StrToDate(children.get(0), children.get(1));
    }

    @Override
    public List<FunctionSignature> getSignatures() {
        return SIGNATURES;
    }

    @Override
    public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
        return visitor.visitStrToDate(this, context);
    }
}
